package com.qf.zyh.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
    //创建对象来存储Connection连接
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();
    //创建线程池
    private static DruidDataSource ds;

    static {
        try {
            Properties PRO = new Properties();
            //添加配置文件到对象中
            PRO.load(DBUtil.class.getResourceAsStream("/jdbc.properties"));
            //通过数据库线程池来获取连接
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(PRO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConn(){
        //获取连接对象中的连接
        Connection conn = THREAD_LOCAL.get();
        try {
            //判断连接是否为空
            if (conn==null){
                //为空则创建连接，并存储到连接对象中。
                conn = ds.getConnection();
                THREAD_LOCAL.set(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //返回连接
        return conn;
    }


    public static void colseAll(Connection conn, PreparedStatement ps, ResultSet rs){
        try {
            if (rs!=null){
                rs.close();
            }
            if (ps!=null){
                ps.close();
            }
            if (conn!=null){
                //关闭连接时清除连接对象存储的连接
                conn.close();
                THREAD_LOCAL.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void closeCno(){
        Connection conn = getConn();
        try {
            conn.close();
            THREAD_LOCAL.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    public static void begin(){
        Connection conn = getConn();
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            colseAll(conn,null,null);
        }
    }
    public static void commit(){
        Connection conn = getConn();
        try {
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            colseAll(conn,null,null);
        }
    }
    public static void rollback(){
        Connection conn = getConn();
        try {
            conn.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            colseAll(conn,null,null);
        }
    }
}
